<?php
//if(intval(time())>1446966000){
//	die('-1');
//}

//die('-1');

define("_needlogin", "1");
define("_access", "1");
define("_defend", "0");
include_once("../include/db.config.php"); 

$chalId = (int)$_GET['chalId'];
$nonce  = md5(md5($_SESSION['team']['password']));
$teamId = (int)$_SESSION['team']['id'];
$time = time();

//var_dump($_SESSION);

if($teamId == 0){
	die('-1');
}

if($_POST['nonce'] !== $nonce){
	die('-1');
}
$key = $_POST['key'];

$sql = "SELECT * from team where id='$teamId'";
$r = getOne($sql);

//爆破检测
if(((int)$time-$r['lastsubmit'])<5){
	die("3");
}

//echo $r['solves'];

if(!empty($r['solves'])){
	$arr = explode(',', $r['solves']);
	foreach ($arr as $key => $value) {
		if((int)$value === $chalId){
			echo 2;
			die();
		}
	}
}

$sql = "SELECT * from challenge where id='$chalId' and enable=1";
$chalInfo = getOne($sql);

$value = $chalInfo['value']; //分值
$flag = $chalInfo['flag']; //flag
$chalType = $chalInfo['category']; //提交类型
$rank = intval($chalInfo['solves'])+1; //提交名次





//

if($flag === md5($_POST['key'])){
	//对了！
	$solves = $r['solves'];
	$solves .= (','.$chalId);

	//名次
	/*
	if($rank <= 3 && $chalType != 'BASIC'){
		$plusPercent = 0.05*(4-$rank);
		$plus = intval($value*$plusPercent);
	}else{
		$plus = 0;
	}
	*/

	$plus = 0;

	$sql = "INSERT into submitLog (teamId,challengeId,flag,plus,rank)values($teamId,$chalId,'$flag',$plus,$rank)";
	mysql_query($sql) or die('error0');
	$value += $plus;


	$sql = "UPDATE team SET solves='$solves',score=score+$value,lastsubmit=$time where id='$teamId'";
	mysql_query($sql) or die('error1');
	$sql = "UPDATE challenge SET solves=solves+1 where id='$chalId'";
	mysql_query($sql) or die('error2');
	echo 1;
	die();
}else{
	echo 0;
	die();
}